import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:uuid/uuid.dart';
import '../models/user.dart';

class UserService {
  static const String _usersKey = 'users';
  static const String _currentUserKey = 'current_user';
  
  // 获取所有用户
  Future<List<User>> getAllUsers() async {
    final prefs = await SharedPreferences.getInstance();
    final usersJson = prefs.getStringList(_usersKey) ?? [];
    
    return usersJson.map((userStr) => 
      User.fromJson(jsonDecode(userStr))
    ).toList();
  }
  
  // 根据ID获取用户
  Future<User?> getUserById(String id) async {
    final users = await getAllUsers();
    return users.firstWhere((user) => user.id == id, orElse: () => throw Exception('User not found'));
  }
  
  // 根据用户名获取用户
  Future<User?> getUserByUsername(String username) async {
    final users = await getAllUsers();
    try {
      return users.firstWhere((user) => user.username == username);
    } catch (e) {
      return null;
    }
  }
  
  // 添加用户
  Future<User> addUser(User user) async {
    final prefs = await SharedPreferences.getInstance();
    final users = await getAllUsers();
    
    // 检查用户名是否已存在
    final existingUser = users.where((u) => u.username == user.username).toList();
    if (existingUser.isNotEmpty) {
      throw Exception('Username already exists');
    }
    
    // 生成新的用户ID
    final newUser = user.copyWith(id: const Uuid().v4());
    
    // 添加新用户
    users.add(newUser);
    await _saveUsers(users);
    
    return newUser;
  }
  
  // 更新用户
  Future<User> updateUser(User user) async {
    final users = await getAllUsers();
    final index = users.indexWhere((u) => u.id == user.id);
    
    if (index == -1) {
      throw Exception('User not found');
    }
    
    users[index] = user;
    await _saveUsers(users);
    
    return user;
  }
  
  // 删除用户
  Future<void> deleteUser(String id) async {
    final users = await getAllUsers();
    users.removeWhere((user) => user.id == id);
    await _saveUsers(users);
  }
  
  // 保存当前用户
  Future<void> saveCurrentUser(User user) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_currentUserKey, jsonEncode(user.toJson()));
  }
  
  // 获取当前用户
  Future<User?> getCurrentUser() async {
    final prefs = await SharedPreferences.getInstance();
    final userJson = prefs.getString(_currentUserKey);
    
    if (userJson == null) {
      return null;
    }
    
    return User.fromJson(jsonDecode(userJson));
  }
  
  // 清除当前用户
  Future<void> clearCurrentUser() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.remove(_currentUserKey);
  }
  
  // 用户登录
  Future<User> login(String username, String password) async {
    final user = await getUserByUsername(username);
    
    if (user == null) {
      throw Exception('User not found');
    }
    
    if (user.password != password) {
      throw Exception('Incorrect password');
    }
    
    await saveCurrentUser(user);
    return user;
  }
  
  // 用户注销
  Future<void> logout() async {
    await clearCurrentUser();
  }
  
  // 初始化默认用户
  Future<void> initDefaultUsers() async {
    final users = await getAllUsers();
    
    // 如果已经有用户，则不初始化
    if (users.isNotEmpty) {
      return;
    }
    
    // 创建四个默认用户
    final defaultUsers = [
      User(
        id: const Uuid().v4(),
        username: 'user1',
        password: '123456',
        nickname: 'Alex',
        avatar: 'avatar1',
        birth: '1990-01-15',
        signature: 'Life is a journey, not a destination.',
        follow: [],
      ),
      User(
        id: const Uuid().v4(),
        username: 'user2',
        password: '123456',
        nickname: 'Emma',
        avatar: 'avatar2',
        birth: '1992-05-20',
        signature: 'Dream big, work hard, stay focused.',
        follow: [],
      ),
      User(
        id: const Uuid().v4(),
        username: 'user3',
        password: '123456',
        nickname: 'Michael',
        avatar: 'avatar3',
        birth: '1988-11-07',
        signature: 'Embrace the glorious mess that you are.',
        follow: [],
      ),
      User(
        id: const Uuid().v4(),
        username: 'user4',
        password: '123456',
        nickname: 'Sophia',
        avatar: 'avatar4',
        birth: '1995-08-30',
        signature: 'Be yourself, everyone else is already taken.',
        follow: [],
      ),
    ];
    
    await _saveUsers(defaultUsers);
  }
  
  // 用户注册
  Future<User> register({
    required String username,
    required String password,
    required String nickname,
    String? signature,
  }) async {
    // 检查用户名是否已存在
    final existingUser = await getUserByUsername(username);
    if (existingUser != null) {
      throw Exception('用户名已存在');
    }
    
    // 创建新用户
    final newUser = User(
      id: const Uuid().v4(),
      username: username,
      password: password,
      nickname: nickname,
      avatar: 'avatar1', // 默认头像
      birth: '2000-01-01', // 默认生日
      signature: signature ?? '', // 个性签名
      follow: [], // 初始关注列表为空
    );
    
    // 添加用户
    final users = await getAllUsers();
    users.add(newUser);
    await _saveUsers(users);
    
    return newUser;
  }
  
  // 保存用户列表
  Future<void> _saveUsers(List<User> users) async {
    final prefs = await SharedPreferences.getInstance();
    final usersJson = users.map((user) => jsonEncode(user.toJson())).toList();
    await prefs.setStringList(_usersKey, usersJson);
  }
} 